package cx.v1.util;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.Security;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openssl.PEMReader;

public class Claves {
    
    public Claves() {
    }
    
    public static PrivateKey getClavePrivadaPEM(String pem)throws Exception
    {
        return getClavePrivadaPEM(pem, null);
    }
    
    public static PrivateKey getClavePrivadaPEM(String pem, String password) throws Exception
    {
        try
        {
            Security.addProvider(new BouncyCastleProvider());
            InputStream in = new FileInputStream(pem);        
            PEMReader reader = null;
            if(password != null)
            {
                reader = new PEMReader(new InputStreamReader(in), new Password(password));
            }
            else
            {
                reader = new PEMReader(new InputStreamReader(in));
            }
            
            KeyPair keyPair = (KeyPair) reader.readObject();
            PrivateKey privateKey = keyPair.getPrivate();
            
            return privateKey;
        }
        catch(Exception ex)
        {
            if(ex instanceof FileNotFoundException){
                throw new Exception("Error: El archivo en formato PEM no existe");
            }
            else if(ex instanceof IOException){
                throw new Exception("Error: No existe proveedor: BC");
            }
            else{
                throw new Exception(ex.getMessage());
            }
        }
    }
    
}
